package com.hieu.android.designpattern.observer;

import java.util.ArrayList;
import java.util.List;

public class MyTopic implements Subject {

	private List<Observer> observers;
	private int idUI;
	private String title;
	private String message;
	private boolean changed;
	private final Object MUTEX= new Object();

	public MyTopic(int id, String title) {
		this.idUI = id;
		this.title = title;
		this.observers=new ArrayList<Observer>();
	}
	
	public int getidUI() {
		return idUI;
	}
	
	public String getTitle() {
		return title;
	}
	
	public MyTopic(TopicState st) {
		if (st == TopicState.start) {
			message = "Start";
		} else if (st == TopicState.pause) {
			message = "Pause";
		} else {
			message = "Stop";
		}
	}

	@Override
	public void register(Observer obj) {
		if(obj == null) {
			throw new NullPointerException("Null Observer");
		}
		synchronized (MUTEX) {
			if(!observers.contains(obj)) {
				observers.add(obj);
			}
		}
	}

	@Override
	public void unregister(Observer obj) {
		synchronized (MUTEX) {
			observers.remove(obj);
		}
	}

	@Override
	public void notifyObservers() {
		List<Observer> observersLocal = null;
		/**
		 * synchronization is used to make sure any observer registered 
		 * after message is received is not notified
		 */
		synchronized (MUTEX) {
			if (!changed)
				return;
			observersLocal = new ArrayList<Observer>(this.observers);
			this.changed=false;
		}
		for (Observer obj : observersLocal) {
			obj.update();
		}
	}

	@Override
	public Object getUpdate(Observer obj) {
		return this.message;
	}

	//method to post message to the topic
	public void postMessage(String msg) {
		this.message=msg;
		this.changed=true;
		notifyObservers();
	}
	
	enum TopicState {
		start,
		pause,
		stop,
	}
}
